<template>
  <div>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="70%" :before-close="resetForm">
      <!-- 2、表单 -->
      <div class="myform">
        <el-form :model="accessoryForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="设备号" prop="equipment">
            <el-input v-model="accessoryForm.equipment" disabled></el-input>
          </el-form-item>
          <el-form-item label="PM计划者组名称" prop="Name_of_PM_Planner_Group">
            <el-input v-model="accessoryForm.Name_of_PM_Planner_Group"></el-input>
          </el-form-item>
          <el-form-item label="组件编码" prop="Component_encoding">
            <el-input v-model="accessoryForm.Component_encoding"></el-input>
          </el-form-item>
          <el-form-item label="编码物料描述" prop="Code_material_description">
            <el-input v-model="accessoryForm.Code_material_description"></el-input>
          </el-form-item>
          <el-form-item label="库存数量" prop="Inventory_quantity">
            <el-input v-model="accessoryForm.Inventory_quantity"></el-input>
          </el-form-item>
          <el-form-item label="密封图纸" prop="Sealing_drawing">
                <el-button type="primary" @click="innerVisibleImg = true">上传图片</el-button>
                <img :src="accessoryForm.Sealing_drawing" style="width: 100px;vertical-align: middle;margin-left: 10px;">
            </el-form-item>
          <el-form-item label="富文本编辑器" prop="descs">
            <!-- 富文本编辑器 -->

            <wangEditor ref="myEditor" @sendEditor="getEditor" />
          </el-form-item>
        </el-form>
      </div>

      <!-- 弹窗底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm">取 消</el-button>
        <el-button type="primary" @click="submitForm" @changePage="changePage">确 定</el-button>
      </span>

      <!-- 1、内弹框 类目选择 -->
      <el-dialog width="30%" title="类目选择" :visible.sync="innerVisible" append-to-body>

        <!-- 树型结构 -->
        <TreeView @sendTreeData="sendTreeData" />

        <!-- 弹窗底部按钮 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="innerVisible = false">取 消</el-button>
          <el-button type="primary" @click="showTreeData">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 2、内弹框 图片上传 -->
      <el-dialog width="30%" title="图片上传" :visible.sync="innerVisibleImg" append-to-body>

        <!-- 图片上传 -->
        <uploadImg @sendImg="getImgUrl" />

        <!-- 弹窗底部按钮 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="innerVisibleImg = false">取 消</el-button>
          <el-button type="primary" @click="showImgURL">确 定</el-button>
        </span>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import TreeView from "./TreeView.vue"
import uploadImg from "@/components/common/uploadImg.vue"
import wangEditor from "@/components/common/wangEditor.vue"
import { addAccessory, updateAccessory, getCategoryData } from "@/api/index.js"
export default {
  props: {
    title: {
      type: String,
      default: function () {
        return "";
      }
    },
    rowData: {
      type: Object,
      default: function () {
        return {};
      }
    }
  },
  components: {
    TreeView,
    uploadImg,
    wangEditor
  },
  data() {
    return {
      dialogVisible: false,  //控制显示隐藏
      innerVisible: false,  //控制内弹框显示隐藏（默认是隐藏）
      innerVisibleImg: false,  //图片上传内弹窗显示隐藏
      treeData: {}, // tree
      isShowParams: false,  //是否显示规格参数，默认隐藏
      paramInfo: [],  //规格参数数组
      imgURL: '', // 图片路径
      // 表单数据对象
      accessoryForm: {
        id: '',
        equipment: '',
        Name_of_PM_Planner_Group: '',
        Component_encoding: '',
        Code_material_description: '',
        equipment_classification: '',
        Sealing_drawing: '',
        manufacturer: '',
        rated_flow_rate: '',
        Inventory_quantity: '',
        image: '',
        shellPoint: '',
        price: '',
        cid: '',
        num: '',        
        descs: '',
        category: ''

       








      },
      rules: {
        title: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        num: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ]
      }
    };
  },
  mounted() {
    

  },
  //侦听器：侦听到属性的变化之后
  watch: {
    rowData(val) {
      console.log("tt",val);
      this.accessoryForm = val;
      console.log('yyu',this.accessoryForm.device_number)
      // editor.txt.html('<p>xxxxx</p>')    //重新设置编辑器内容
      // data、computed、props、watch、method 在created的时候已经初始化完成了,所以找不到DOM元素
      // 延时操作DOM
      this.$nextTick(() => {  //获取到DOM元素才执行
        this.$refs.myEditor.editor.txt.html(val.descs);
      })

      //两次点击同一条数据，修改商品表单，第二次没数据==》原因：侦听器没有侦听到rowData值的滨化

      //是否显示规格参数
      if (val.paramsInfo) {
        //显示
        this.isShowParams = true;
        this.paramInfo = JSON.parse(val.paramsInfo);
      }
    }
  },
  methods: {
    // 接收tree子组件传递过来的数据，选择的是哪个节点
    sendTreeData(val) {
      this.treeData = val;
    },
    // 接收上传图片子组件传递过来的图片路径
    getImgUrl(url) {
      this.imgURL = url;
    },
    // 展示图片
    showImgURL() {
      // 图片上传弹窗隐藏
      this.innerVisibleImg = false;
      // 再将图片路径复制给accessoryFor显示
      this.accessoryForm.Sealing_drawing = this.imgURL;
    },
    // 展示点击的tre节点
    async showTreeData() {
      // 隐藏内弹窗
      this.innerVisible = false;
      // 展示类目 {id:'',cid:'',name:''}
      this.accessoryForm.category = this.treeData.name;
      this.accessoryForm.cid = this.treeData.cid;

      // 是否显示规格参数，请求后台
      try {
        const res = await getCategoryData({ cid: this.treeData.cid });
        console.log(res);
        if (res.status === 200) {
          // 显示规格参数
          this.isShowParams = true;
          let info = res.result[res.result.length - 1];
          // console.log(info);
          this.paramInfo = JSON.parse(info.paramData);
          console.log(this.paramInfo);
        } else {
          // 没有参数配置，隐藏
          this.isShowParams = false;
        }
      } catch (error) {
        console.log(error);
      }
    },
    // 获取editor数据
    getEditor(val) {
      this.accessoryForm.descs = val;
    },
    // 提交表单
    // 参数： title cid  category sellPoint price num desc paramsInfo image
    
    
    
    submitForm(formName) {  // eslint-disable-line no-unused-vars
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          console.log("dafas", this.accessoryForm);

          //对象合并  let obj1 = Object.assign(obj1,obj2);  //将obj2合并到obj1上变成一个新的obj1
          Object.assign(this.accessoryForm, {
            paramsInfo: JSON.stringify(this.paramInfo)
          })

          if (this.title === "配件添加") {
            try {
              const res = await addAccessory(this.accessoryForm);
              console.log(res.status);
              if (res.status == 200) {  //成功

                this.$parent.getAccessoryList(1);  // 更新父组件列表数据
                this.changePage()  //让页码在在第一页高亮
                this.$message({
                  message: '恭喜你，添加成功！',
                  type: 'success'
                });
                // 清空表单
                this.resetForm();
              } else {
                this.$message.error('添加失败.....');
              }
            } catch (error) {
              console.log(error);
              this.$message.error('填写错误，请检查数据!!!');
            }
          } else {
            console.log('编辑', this.accessoryForm);
            // 参数：id title cid  category sellPoint price num desc paramsInfo image
            try {
              const res = await updateAccessory(this.accessoryForm);
              console.log(res);
              if (res.status == 200) {  //成功

                this.$parent.getAccessoryList(1);  // 更新父组件列表数据
                this.changePage()  //让页码在在第一页高亮
                this.$message({
                  message: '修改配件信息成功！',
                  type: 'success'
                });
                // 清空表单
                this.resetForm();
              } else {
                this.$message.error('修改设备失败.....');
              }
            } catch (error) {
              console.log(error);
              this.$message.error('填写错误，请检查数据.....');
            }
          }
        } else {
          console.log('error submit!!');
          this.$message.error('填写错误，请检查数据。。。。。');
          return false;
        }
      });
    },
    // 添加或编辑商品子组件触发页码改变事件
    changePage(page) {
      this.$emit("changePage", page);  // 自定义事件（子传父）
    },
    // 重置表单
    resetForm(formName) { // eslint-disable-line no-unused-vars
      // this.$refs[formName].resetFields();

      // 1、隐藏弹窗
      this.dialogVisible = false;
      // 2、清空表单
      // 表单数据对象
      this.accessoryForm = {
        cid: '',
        category: '',  //类目
        title: '',   //商品名称
        price: '',   //价格
        num: '',   //数量
        date1: '',
        date2: '',
        sellPoint: '',  //卖点
        image: '',   //上传图片
        descs: ''   //描述
      }
      // 3、清空富文本    editor.txt.clear()
      this.$refs.myEditor.editor.txt.clear();
      // 清空规格参数
      this.paramInfo = [];
      this.isShowParams = false;
    }
  }
};
</script>

<style lang="less" scoped>
.myform {
  padding: 20px;

  .line {
    text-align: center;
  }
}
</style>
